package interceptor;

import java.util.Map;

import org.apache.struts2.dispatcher.RequestMap;
import org.apache.struts2.dispatcher.SessionMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

import dao.CategoryDAO;
import dao.DeviceBrandDAO;
import dao.OperatingSystemDAO;
import dao.PriceDAO;
import dao.CarrierDAO;
import dao.CustomerReviewDAO;
import dao.UserDAO;

public class CommonDataInterceptor implements Interceptor{

    
    /**
	 * 
	 */
	private static final long serialVersionUID = 3964481445241495235L;

	@Autowired
	private CategoryDAO CategoryDAO;
	
	@Autowired
	private PriceDAO PriceDAO;
	
	@Autowired
	private DeviceBrandDAO DeviceBrandDAO;
	
	@Autowired
	private CarrierDAO CarrierDAO;
	
	@Autowired
	private OperatingSystemDAO OperatingSystemDAO;
	
	@Autowired
	private CustomerReviewDAO CustomerReviewDAO;
	
	@Autowired
	private UserDAO UserDAO;
	
	public void destroy() {
        System.out.println("Destroying CommonDataInterceptor ...");
    }

    
    public void init() {
        System.out.println("Initializing CommonDataInterceptor ...");
    }

    
    @SuppressWarnings({ "unchecked", "rawtypes" })
	public String intercept(ActionInvocation ai) throws Exception {
        RequestMap map = (RequestMap)ai.getInvocationContext().get("request");
        Map session = ActionContext.getContext().getSession();
        
        map.put("categories", CategoryDAO.getListCategory());
        
        map.put("lstPrice", PriceDAO.getListPrice());
        map.put("lstDeviceBrand", DeviceBrandDAO.getListDeviceBrand());
        map.put("lstCarrier", CarrierDAO.getListCarrier());
        map.put("lstOS", OperatingSystemDAO.getListOS());
        map.put("lstReview", CustomerReviewDAO.getListCustomerReview());
        
        try
        {
        	if (session.get("lastname") == null)
        	{
        		session.put("lastname", UserDAO.getLasName(((User)SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername()));
        		session.put("isAdmin", UserDAO.isAdmin(((User)SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername()));
        	}
        }
        catch (Exception ex){
        	
        }
        
        return ai.invoke();
        
    }
    
}
